package com.seecen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seecen.common.BaseResponse;
import com.seecen.common.PageRequest;
import com.seecen.common.ResultUtils;
import com.seecen.exception.ErrorCode;
import com.seecen.mapper.OrderMapper;
import com.seecen.pojo.dto.EvaluationAddRequest;
import com.seecen.pojo.entity.Evaluation;

import com.seecen.pojo.entity.Order;
import com.seecen.pojo.entity.Order;
import com.seecen.pojo.entity.User;
import com.seecen.service.EvaluationService;
import com.seecen.mapper.EvaluationMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aot.hint.annotation.Reflective;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.seecen.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author 小辛
* @description 针对表【allmaster_evaluation(用户评价表)】的数据库操作Service实现
* @createDate 2025-10-17 23:14:39
*/
@Service
@Slf4j
public class EvaluationServiceImpl extends ServiceImpl<EvaluationMapper, Evaluation>
    implements EvaluationService{

    @Autowired
    private OrderMapper orderMapper;

    @Resource
    private EvaluationMapper evaluationMapper;
    @Override
    public BaseResponse<?> getAllEvaluations(PageRequest pageRequest) {
        try {

            Page<Evaluation> page = new Page<>(pageRequest.getCurrent(), pageRequest.getPageSize());
            QueryWrapper<Evaluation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("isDeleted", 0)
                    .orderByDesc("createTime");

            IPage<Evaluation> evaluationPage = this.page(page, queryWrapper);

            Map<String, Object> data = new HashMap<>();
            data.put("total", evaluationPage.getTotal());
            data.put("list", evaluationPage.getRecords());
            data.put("pageSize", evaluationPage.getSize());
            data.put("currentPage", evaluationPage.getCurrent());

            return ResultUtils.success(data);
        } catch (Exception e) {
            log.error("获取所有评价列表失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "获取评价列表失败");
        }
    }


    @Override
    public BaseResponse<?> addIndexEvaluation(EvaluationAddRequest request) {
        try {
            // 数据校验
            if (request.getScore() == null || request.getScore() < 1 || request.getScore() > 5) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "评分必须在1-5分之间");
            }
            if (request.getOrderid() == null) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "订单ID不能为空");
            }
            if (request.getServiceid() == null) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "服务ID不能为空");
            }
            if (request.getContent() == null || request.getContent().trim().isEmpty()) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "评价内容不能为空");
            }

            // 根据订单ID查询订单信息，获取用户ID
            Order order = orderMapper.selectById(request.getOrderid());
            if (order == null) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "订单不存在");
            }
            if (order.getIsdeleted() != null && order.getIsdeleted() == 1) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "订单已被删除");
            }

            // 从订单中获取用户ID
            Long userId = order.getUserid();
            if (userId == null) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "订单用户信息异常");
            }

            // 检查该订单是否已经评价过
            QueryWrapper<Evaluation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("orderid", request.getOrderid())
                       .eq("userid", userId)
                       .eq("isdeleted", 0);

            Evaluation existingEvaluation = this.getOne(queryWrapper);
            if (existingEvaluation != null) {
                return ResultUtils.error(ErrorCode.OPERATION_ERROR, "该订单已经评价过了");
            }

            // 创建评价实体对象
            Evaluation evaluation = new Evaluation();
            evaluation.setOrderid(request.getOrderid());
            evaluation.setServiceid(request.getServiceid());
            evaluation.setUserid(userId); // 从订单中获取的用户ID
            evaluation.setScore(request.getScore());
            evaluation.setContent(request.getContent());

            // 处理图片URL：前端传递imageUrl，数据库字段是imageUrl
            if (request.getImageUrl() != null && !request.getImageUrl().trim().isEmpty()) {
                evaluation.setImageUrl(request.getImageUrl());
                System.out.println("imageUrl: " + request.getImageUrl());
            }

            // 设置城市信息
            if (request.getCity() != null && !request.getCity().trim().isEmpty()) {
                evaluation.setCity(request.getCity());
            } else {
                evaluation.setCity("未知城市");
            }

            // 填充默认值
            evaluation.setCreatetime(new Date());
            evaluation.setUpdatetime(new Date());
            evaluation.setIsdeleted(0);

            // 保存数据
            boolean saveResult = this.save(evaluation);
            if (!saveResult) {
                return ResultUtils.error(ErrorCode.OPERATION_ERROR, "评价提交失败");
            }

            log.info("用户 {} 成功提交评价，订单ID: {}, 图片URL: {}", userId, request.getOrderid(), request.getImageUrl());
            return ResultUtils.success("评价提交成功，感谢您的反馈！");
        } catch (Exception e) {
            log.error("提交评价时发生错误", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "提交评价时发生错误: " + e.getMessage());
        }
    }

    @Override
    public BaseResponse<?> getIndexEvaluation() {
        List<Evaluation> evaluations = evaluationMapper.selectList(null);
        return ResultUtils.success(evaluations);
    }

    @Override
    public BaseResponse<?> checkOrderEvaluation(Long orderId) {
        try {
            if (orderId == null) {
                log.warn("订单ID为空，无法检查评价状态");
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "订单ID不能为空");
            }

            // 查询该订单是否已有评价
            QueryWrapper<Evaluation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("orderId", orderId);
            queryWrapper.eq("isDeleted", 0); // 只查询未删除的评价

            long count = evaluationMapper.selectCount(queryWrapper);
            boolean hasEvaluation = count > 0;

            log.info("检查订单 {} 评价状态：{}", orderId, hasEvaluation ? "已评价" : "未评价");

            return ResultUtils.success(hasEvaluation);
        } catch (Exception e) {
            log.error("检查订单评价状态异常，订单ID: {}", orderId, e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "检查评价状态失败: " + e.getMessage());
        }
    }
}




